const fs = require('fs');
const PizZip = require('pizzip');
const Docxtemplater = require('docxtemplater');
const path = require('path');

class WordProcessor {
  /**
   * 处理Word模版
   * @param {string} templatePath - 模版文件路径
   * @param {object} data - 要替换的数据
   * @param {string} outputPath - 输出文件路径
   */
  static async processTemplate(templatePath, data, outputPath) {
    try {
      // 读取模版文件
      const content = fs.readFileSync(templatePath, 'binary');
      
      // 创建zip实例
      const zip = new PizZip(content);
      
      // 创建docxtemplater实例
      const doc = new Docxtemplater(zip, {
        paragraphLoop: true,
        linebreaks: true,
      });
      
      // 渲染文档并设置数据
      doc.render(data);
      
      // 生成输出文件
      const buf = doc.getZip().generate({
        type: 'nodebuffer',
        compression: 'DEFLATE',
      });
      
      // 写入文件
      fs.writeFileSync(outputPath, buf);
      
      return {
        success: true,
        message: '文档生成成功',
        outputPath
      };
    } catch (error) {
      console.error('处理Word模版时出错:', error);
      return {
        success: false,
        message: error.message
      };
    }
  }
  
  /**
   * 批量处理模版
   * @param {string} templatePath - 模版文件路径
   * @param {Array} dataList - 数据列表
   * @param {string} outputDir - 输出目录
   */
  static async batchProcess(templatePath, dataList, outputDir) {
    const results = [];
    
    for (let i = 0; i < dataList.length; i++) {
      const data = dataList[i];
      const outputPath = path.join(outputDir, `document_${i + 1}.docx`);
      
      const result = await this.processTemplate(templatePath, data, outputPath);
      results.push({
        index: i + 1,
        data,
        ...result
      });
    }
    
    return results;
  }
}

module.exports = WordProcessor;